package cn.itcast.web.aop;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * 声明切面类： @Aspect
 */
@Component
@Aspect
public class LogAspect {

	@Autowired
	private SysLogService sysLogService;

	@Autowired
	private HttpSession session;

	@Autowired
	private HttpServletRequest request;

	/**
	 * 配置环绕通知的方法
	 *  返回值：被代理对象的返回值（object）
	 *  参数： ProceedingJoinPoint
	 *          * 被代理对象的方法：method
	 */
	@Around(value="execution(* cn.itcast.web.controller.*.*.*(..))")
	public Object aroubd(ProceedingJoinPoint pjp) throws Throwable {
		//1.增强:将用户操作保存到系统日志表中
		SysLog log = new SysLog();
		User user = (User) session.getAttribute("loginUser");
		log.setUserName(user.getUserName());
		log.setTime(new Date());
		log.setIp(request.getRemoteAddr()); //通过request获取操作人的IP地址
		log.setCompanyId(user.getCompanyId());
		log.setCompanyName(user.getCompanyName());


		//方法标记对象
		MethodSignature ms = (MethodSignature)pjp.getSignature();
		Method method = ms.getMethod();
		String methodName = method.getName();
		log.setMethod(methodName);
		//判断方法上是否具有RequestMapping注解
		if(method.isAnnotationPresent(RequestMapping.class)) {
			RequestMapping mapping = method.getAnnotation(RequestMapping.class);
			String action = mapping.name();
			log.setAction(action);
		}

		sysLogService.save(log);
		//2.调用被代理对象的方法
		return pjp.proceed();
	}
}
